#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

int main() {
    
    int fd = open("log", O_RDONLY);
    if (fd == -1) {
        perror("open");
        return 1;
    }

    /* lseek: get file size */
    off_t file_size = lseek(fd, 0, SEEK_END);

    /* mmap: cast file content in buffer to user memory space */
    if (file_size <= 0) {
        perror("lseek");
        return 1;
    }
    char *mapped = mmap(NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
    if (mapped == MAP_FAILED) {
        perror("mmap");
        return 1;
    }

    /* print the content of file, use mmap pointer */
    write(STDOUT_FILENO, mapped, file_size);

    /* unmmap: remove file content cast in user memory space */
    munmap(mapped, file_size);

    close(fd);
    
    return 0;
}
